#include <WProgram.h>
#include <stdint.h>
#include <stdio.h>
#include "maxim.h"
#include "utils.h"

//extern adb_connection* adbConnection;

// From Maxim 11068 guide.
uint8_t crc8(uint8_t* data, uint8_t len, uint8_t crc)
{
  while (len--) {
    uint8_t rem = crc ^ *data++;
    for (uint8_t i=0; i<8; i++) {
      if ((rem & 0x80) == 0x80) {
        rem = (rem << 1) ^ 0x7;
      } else {
        rem <<= 1;
      }
    }
    crc = rem;
  }
  return crc;
}

boolean readCmd(char* buf, int bufSize)
{
  int bufLen = bufSize - 1;     // for EOS

   delay(200);
   int n = Serial.available();
   if (n > bufLen) {
     Serial.flush();
     Serial.print("Cmd must be only so many chars: "); 
     Serial.println(bufLen);
     return false;
   }    

   int i;
   for (i=0; i<n;i++) {
     buf[i] = Serial.read();
   }
   
   buf[i] = '\0';
   return true;
}


void hex2str(uint8_t num, char* buf) 
{
  snprintf(buf,2,"%2.2X",(int)num);
}  

void hex2str(uint16_t num, char* buf) 
{
  snprintf(buf,4,"%4.4X",(int)num);
}  

// BUGBUG -- doesn't verify hex string is passed in. upto caller.
void str2hex(char* buf, uint8_t& num)
{
  uint8_t c = buf[0];
  num = (c>'9'?c-'A'+10:c-'0') << 4;
  c = buf[1];
  num |= (c>'9'?c-'A'+10:c-'0');
}


